<template>
  <div class="app-container">
    <el-card title=''>
      <!-- 顶部操作按钮 -->
      <div style="margin-bottom: 16px;">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddCategory">
          新增分类
        </el-button>
        <el-button type="success" icon="el-icon-upload2" @click="handleImport">
          导入分类
        </el-button>
        <el-button type="warning" icon="el-icon-download" @click="handleExport">
          导出分类
        </el-button>
      </div>

      <!-- 树形组件 -->
      <el-tree
        :data="categoryList"
        :props="treeProps"
        node-key="categoryId"
        :default-expand-all="true"
        style="width: 100%"
        v-loading="loading"
        @node-contextmenu="handleRightClick"
      >
        <template #default="{ node, data }">
          <div class="tree-node-content">
            <!-- 左侧斜体显示创建时间和更新时间 -->
            <div class="category-time" style="font-style: italic; color: #909399; margin-right: 15px; min-width: 320px;">
              创建: {{ formatDate(data.createdAt) }}
              更新: {{ formatDate(data.updatedAt) }}
            </div>

            <i
              v-if="data.extField1 && !['fa-times', 'fa-remove', 'fa-close'].some(icon => data.extField1.trim().includes(icon))"
              :class="['fa', data.extField1.trim()]"
              style="font-size: 18px; margin-right: 8px;"
            />
            <!-- 分类悬停显示备注 -->
            <el-tooltip
              effect="dark"
              placement="top"
              :disabled="!data.description"
            >
              <div slot="content" class="tooltip-content">
                {{ data.description }}
              </div>
              <span class="category-name">{{ data.categoryName }}</span>
            </el-tooltip>
            <!-- 右侧操作区 -->
            <div class="operation-area">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(data)"
              >
                修改
              </el-button>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(data)"
              >
                删除
              </el-button>
              <el-switch
                v-model="data.status"
                :active-value="1"
                :inactive-value="0"
                size="small"
                style="margin-left: 10px;"
                @change="handleStatusChange(data)"
              />
              <el-tag :type="data.status === 1 ? 'success' : 'danger'" size="mini" style="margin-left: 8px;">
                {{ data.status === 1 ? '启用' : '禁用' }}
              </el-tag>
              <span class="ext-weight" style="margin-left: 8px; color: #909399;">
                (权重: {{ data.extField3 }})
              </span>
            </div>
          </div>
        </template>
      </el-tree>

      <!-- 分类统计图表区域 -->
      <el-divider>分类统计</el-divider>
      <div class="chart-container">
        <el-row :gutter="20">
          <!-- 柱状图：父分类子分类数量统计 -->
          <el-col :span="12">
            <el-card>
              <div slot="header" class="clearfix">
                <span>子分类数量统计</span>
              </div>
              <div id="barChart" class="chart" style="height: 400px;"></div>
            </el-card>
          </el-col>
          <!-- 饼图：父分类子分类占比统计（含百分比显示） -->
          <el-col :span="12">
            <el-card>
              <div slot="header" class="clearfix">
                <span>子分类占比统计</span>
                <el-checkbox
                  v-model="showAllCategories"
                  size="mini"
                  @change="handleShowAllChange"
                  style="margin-left: 10px;"
                >显示全部</el-checkbox>
              </div>
              <div id="pieChart" class="chart" style="height: 400px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 子分类详情弹窗 -->
      <el-dialog
        title="子分类详情"
        :visible.sync="childDialogVisible"
        width="50%"
      >
        <el-table :data="currentChildren" border>
          <el-table-column prop="categoryName" label="分类名称" width="200"></el-table-column>
          <el-table-column prop="description" label="分类描述"></el-table-column>
        </el-table>
      </el-dialog>

      <!-- 右键菜单 -->
      <el-dropdown
        ref="dropdown"
        :visible.sync="dropdownVisible"
        placement="bottom-start"
        size="small"
      >
        <span class="dropdown-trigger" style="display: none;"></span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="handleAddChild">新增子分类</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <!-- 分类编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
        <el-form ref="categoryForm" :model="categoryForm" :rules="categoryRules" label-width="120px">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="父分类" prop="parentId">
            <el-select v-model="categoryForm.parentId" placeholder="请选择父分类">
              <el-option :value="0" label="顶级分类" />
              <el-option
                v-for="item in categoryList"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
                :disabled="isDisabledParent(item)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注信息" prop="description">
            <el-input
              v-model="categoryForm.description"
              placeholder="请输入备注信息（选填）"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="分类状态" prop="status">
            <el-switch v-model="categoryForm.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="排序权重" prop="sortOrder">
            <el-input-number v-model="categoryForm.sortOrder" :min="0" :step="10" placeholder="请输入排序权重" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog
        title="确认删除"
        :visible.sync="deleteDialogVisible"
        width="30%"
        :show-close="false"
      >
        <div style="text-align: center; padding: 20px 0;">
          <i class="el-icon-warning" style="font-size: 24px; color: #faad14; margin-right: 10px;"></i>
          <span>确定要删除分类 "{{ deleteCategoryName }}" 吗？</span>
        </div>
        <div style="text-align: center; color: #f56c6c; margin-top: 10px;">
          <span>提示：删除分类将同时删除其下所有子分类</span>
        </div>
        <div slot="footer" style="text-align: center;">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </div>
      </el-dialog>

      <!-- 导入分类对话框 -->
      <el-dialog
        title="导入分类"
        :visible.sync="importDialogVisible"
        width="400px"
      >
        <el-form>
          <el-form-item label="上传Excel文件" required>
            <el-upload
              class="upload-demo"
              ref="upload"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="true"
              accept=".xlsx,.xls"
              :limit="1"
              action="javascript:void(0)"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">
                请上传Excel文件，支持.xlsx和.xls格式，第一行应为表头：父分类、子分类、备注信息、状态
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确定导入</el-button>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getCategoryListWithExt,
  addCategory,
  updateCategoryStatus,
  updateCategory,
  deleteCategory,
  exportCategories,
  importCategories,
  getCategoryStatistics
} from '@/api/translation/translation'

export default {
  data() {
    return {
      categoryList: [],
      loading: false,
      treeProps: { children: 'children', label: 'categoryName' },
      size: 'small',
      dropdownVisible: false,
      currentNode: null,
      dialogVisible: false,
      dialogTitle: '新增分类',
      deleteDialogVisible: false,
      deleteCategoryId: null,
      deleteCategoryName: '',
      categoryForm: {
        categoryId: null,
        categoryName: '',
        parentId: 0,
        description: '',
        status: 1,
        sortOrder: 0
      },
      categoryRules: {
        categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        sortOrder: [{ required: true, message: '请输入排序权重', trigger: 'blur' }],
      },
      importDialogVisible: false,
      selectedFile: null,
      // 图表相关变量
      barChart: null,
      pieChart: null,
      childDialogVisible: false,
      currentChildren: [],
      categoryStatistics: {
        parentNames: [],
        childCounts: [],
        childDetails: {},
        totalChildCount: 0 // 总子分类数量，用于计算百分比
      },
      // 新增：饼图交互相关状态
      showAllCategories: true,  // 是否显示所有分类
      selectedCategories: []    // 选中的分类名称集合
    };
  },
  methods: {
    loadCategoryList() {
      this.loading = true;
      getCategoryListWithExt().then(response => {
        this.categoryList = response;
        this.loading = false;
      }).catch(error => {
        this.$message.error('获取分类列表失败：' + (error.response?.data?.msg || error.message));
        this.loading = false;
      });
    },
    handleStatusChange(data) {
      const originalStatus = data.status === 1 ? 0 : 1;
      this.loading = true;
      updateCategoryStatus(data.categoryId, data.status)
        .then(() => {
          this.$message.success(`分类"${data.categoryName}"${data.status === 1 ? '启用' : '禁用'}成功`);
        })
        .catch(error => {
          data.status = originalStatus;
          this.$message.error(`操作失败: ${error.response?.data?.msg || '网络错误'}`);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleRightClick(event, node, data) {
      event.preventDefault();
      this.currentNode = data;
      this.dropdownVisible = true;
      this.$refs.dropdown.$el.style.left = `${event.clientX}px`;
      this.$refs.dropdown.$el.style.top = `${event.clientY}px`;
    },
    handleAddCategory() {
      this.dialogTitle = '新增顶级分类';
      this.resetForm();
      this.categoryForm.parentId = 0;
      this.dialogVisible = true;
    },
    handleAddChild() {
      this.dialogTitle = '新增子分类';
      this.resetForm();
      this.categoryForm.parentId = this.currentNode.categoryId;
      this.dialogVisible = true;
      this.dropdownVisible = false;
    },
    handleEdit(data) {
      this.dialogTitle = '修改分类';
      this.categoryForm = {
        categoryId: data.categoryId,
        categoryName: data.categoryName,
        parentId: data.parentId || 0,
        description: data.description || '',
        status: data.status,
        sortOrder: data.extField3 || 0
      };
      this.dialogVisible = true;
    },
    handleDelete(data) {
      this.deleteCategoryId = data.categoryId;
      this.deleteCategoryName = data.categoryName;
      this.deleteDialogVisible = true;
    },
    confirmDelete() {
      this.loading = true;
      deleteCategory(this.deleteCategoryId)
        .then(() => {
          this.$message.success('分类删除成功');
          this.deleteDialogVisible = false;
          this.loadCategoryList();
          this.loadCategoryStatistics();
        })
        .catch(error => {
          this.$message.error('删除失败: ' + (error.response?.data?.msg || error.message));
        })
        .finally(() => {
          this.loading = false;
        });
    },
    resetForm() {
      this.categoryForm = {
        categoryId: null,
        categoryName: '',
        parentId: 0,
        description: '',
        status: 1,
        sortOrder: 0
      };
      this.$refs.categoryForm?.resetFields();
    },
    isDisabledParent(item) {
      if (this.categoryForm.categoryId) {
        return item.categoryId === this.categoryForm.categoryId || this.isChildOf(item, this.categoryForm.categoryId);
      }
      return false;
    },
    isChildOf(parent, childId) {
      if (!parent.children || parent.children.length === 0) {
        return false;
      }
      for (let child of parent.children) {
        if (child.categoryId === childId) {
          return true;
        }
        if (this.isChildOf(child, childId)) {
          return true;
        }
      }
      return false;
    },
    submitForm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          const formData = {
            categoryName: this.categoryForm.categoryName,
            parentId: this.categoryForm.parentId === 0 ? null : parseInt(this.categoryForm.parentId, 10),
            description: this.categoryForm.description,
            status: this.categoryForm.status,
            sortOrder: this.categoryForm.sortOrder
          };
          this.loading = true;
          if (this.categoryForm.categoryId) {
            formData.categoryId = this.categoryForm.categoryId;
            updateCategory(formData)
              .then(() => {
                this.$message.success('分类修改成功');
                this.dialogVisible = false;
                this.loadCategoryList();
                this.loadCategoryStatistics();
              })
              .catch(error => {
                this.$message.error('分类修改失败：' + (error.response?.data?.msg || error.message));
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            addCategory(formData)
              .then(() => {
                this.$message.success('分类新增成功');
                this.dialogVisible = false;
                this.loadCategoryList();
                this.loadCategoryStatistics();
              })
              .catch(error => {
                this.$message.error('分类新增失败：' + (error.response?.data?.msg || error.message));
              })
              .finally(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    handleExport() {
      this.loading = true;
      exportCategories().then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '商品分类列表.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        this.$message.success('导出成功');
      }).catch(error => {
        this.$message.error('导出失败: ' + (error.message || '网络错误'));
      }).finally(() => {
        this.loading = false;
      });
    },
    handleImport() {
      this.importDialogVisible = true;
      this.selectedFile = null;
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    handleFileChange(file, fileList) {
      this.selectedFile = file.raw;
    },
    confirmImport() {
      if (!this.selectedFile) {
        this.$message.warning('请选择要导入的Excel文件');
        return;
      }
      this.loading = true;
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      importCategories(formData).then(response => {
        this.$message.success(response.msg || '导入成功');
        this.importDialogVisible = false;
        this.loadCategoryList();
        this.loadCategoryStatistics();
      }).catch(error => {
        this.$message.error('导入失败: ' + (error.response?.data?.msg || error.message || '网络错误'));
      }).finally(() => {
        this.loading = false;
        this.selectedFile = null;
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    formatDate(dateStr) {
      if (!dateStr) return '无';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    // 图表初始化
    initCharts() {
      this.initBarChart();
      this.initPieChart();
      this.loadCategoryStatistics();
    },
    // 初始化柱状图
    initBarChart() {
      this.barChart = echarts.init(document.getElementById('barChart'));
      this.barChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value', name: '子分类数量' },
        series: [{ name: '子分类数量', type: 'bar', data: [], itemStyle: { color: '#5470c6' } }]
      });
    },
    // 初始化饼图（含百分比配置和交互）
    initPieChart() {
      this.pieChart = echarts.init(document.getElementById('pieChart'));
      const initialOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)' // 提示框显示百分比
        },
        legend: {
          orient: 'vertical',
          left: 10,
          selected: {} // 用于存储图例选中状态
        },
        series: [{
          name: '子分类占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {d}%' // 标签显示名称和百分比
          },
          labelLine: { show: true }, // 显示标签连接线
          emphasis: {
            label: { show: true, fontSize: 16, fontWeight: 'bold' }
          },
          data: []
        }]
      };

      this.pieChart.setOption(initialOption);

      // 添加图例点击事件监听
      this.pieChart.on('legendselectchanged', params => {
        this.handleLegendSelectChanged(params);
      });
    },
    // 处理图例选择变化事件
    handleLegendSelectChanged(params) {
      const selected = params.selected;
      const selectedNames = Object.keys(selected).filter(name => selected[name]);

      // 更新选中状态
      this.selectedCategories = selectedNames;
      this.showAllCategories = selectedNames.length === Object.keys(selected).length;

      // 筛选数据并重新计算占比
      this.updatePieChartWithFilter(selectedNames);
    },
    // 显示全部分类
    handleShowAllChange(checked) {
      if (checked) {
        this.selectedCategories = [...this.categoryStatistics.parentNames];
        this.updatePieChartWithFilter(this.selectedCategories);

        // 更新图例选中状态
        const legendSelected = {};
        this.categoryStatistics.parentNames.forEach(name => {
          legendSelected[name] = true;
        });
        this.pieChart.setOption({
          legend: { selected: legendSelected }
        });
      }
    },
    // 根据选中的分类更新饼图数据和占比
    updatePieChartWithFilter(selectedNames) {
      // 筛选数据
      const filteredData = this.categoryStatistics.parentNames
        .map((name, index) => ({
          name,
          value: this.categoryStatistics.childCounts[index]
        }))
        .filter(item => selectedNames.includes(item.name));

      // 计算总和用于占比计算
      const total = filteredData.reduce((sum, item) => sum + item.value, 0);

      // 计算百分比并更新饼图
      const pieData = filteredData.map(item => ({
        name: item.name,
        value: item.value,
        percent: total > 0 ? (item.value / total * 100).toFixed(2) : 0
      }));

      this.pieChart.setOption({
        series: [{
          data: pieData,
          label: {
            formatter: params => `${params.name}: ${params.data.percent}%`
          }
        }]
      });
    },
    // 加载分类统计数据（含百分比计算）
    loadCategoryStatistics() {
      getCategoryStatistics().then(response => {
        this.categoryStatistics = response;

        // 更新柱状图数据
        this.barChart.setOption({
          xAxis: { data: response.parentNames },
          series: [{ data: response.childCounts }]
        });

        // 初始化选中状态
        this.selectedCategories = [...response.parentNames];
        this.showAllCategories = true;

        // 更新饼图数据（计算百分比）
        this.updatePieChartWithFilter(this.selectedCategories);

        // 柱状图点击事件：显示子分类详情
        this.barChart.off('click');
        this.barChart.on('click', (params) => {
          const parentIndex = params.dataIndex;
          const parentId = Object.keys(response.childDetails)[parentIndex];
          this.currentChildren = response.childDetails[parentId] || [];
          this.childDialogVisible = true;
        });
      }).catch(error => {
        this.$message.error('获取统计数据失败: ' + (error.response?.data?.msg || error.message));
      });
    },
    // 窗口大小变化处理
    handleResize() {
      if (this.barChart) this.barChart.resize();
      if (this.pieChart) this.pieChart.resize();
    }
  },
  created() {
    this.loadCategoryList();
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.barChart) this.barChart.dispose();
    if (this.pieChart) this.pieChart.dispose();
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style scoped>
.app-container { padding: 20px; }
.ext-weight { font-size: 12px; color: #909399; margin-left: 8px; }
.dropdown-trigger { display: none !important; }

/* 树形节点容器 */
.tree-node-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
  width: 100%;
}

/* 分类名称样式 */
.category-name {
  margin-left: 8px;
  cursor: pointer;
}

/* 时间显示样式 */
.category-time {
  font-size: 12px;
  line-height: 1.2;
  white-space: nowrap;
}

/* Tooltip样式 */
.tooltip-content {
  max-width: 300px;
  white-space: normal;
}

/* 操作区样式 */
.operation-area {
  display: flex;
  align-items: center;
  margin-left: auto;
  min-width: 380px;
  white-space: nowrap;
}

/* 上传组件样式 */
.upload-demo {
  margin-top: 10px;
}

/* 图表容器样式 */
.chart-container {
  margin-top: 20px;
  padding: 0 10px;
}
.chart {
  width: 100%;
  height: 400px;
}
@media (max-width: 768px) {
  .chart { height: 300px; }
}
</style>
